#!/usr/bin/perl
# Usage: fix_perm [-h]

use Cwd qw(realpath);

sub y_or_n {
    local($prompt) = @_;
    print STDOUT $prompt;
    local($answer) = scalar(<STDIN>);
    $answer =~ /^y/i;
}

sub fix {
    if (-l "@_") {
	@_ = realpath(@_);
    }

    local($directory)= @_;
    $directory =~ /^(.*)\/[^\/]+/;

    if(!-w "$1") {
	print "no write permission for $1, run script as 'root'\n";
    } elsif (-l "@_") {
	print "@_ is a symbolic link, can't fix\n";
    } elsif (-e "@_")  {
	print "Fixing @_ \n";
    system("chown -R oper.rtx @_");
    system("chmod -R ug+rw,o+r,o-w @_");
    } else {
	print "No @_ directory\n";
    }
}
if ($#ARGV >= 0) {
    print "Usage: fix_perm [-h]\n";
    print "\n";
    print "Fixes permissions for operator files in /usr2/control,\n";
    print "/usr2/proc, /usr2/log/, /usr2/sched, and /usr2/tle_files \n";
    print "\n";
    print "Symbolic links are resolved.\n";
    print "\n";
    print "Prompts for permssion before proceeding.\n";
    print "\n";
    print "Must be executed by root\n";
    print "\n";
    print "  Command line option '-h' (or any other argument) displays this message\n";

    exit -1;
}

print "*****************************************************************************\n";
print "*  This script will 'fix' the ownership and permissions of the directories  *\n";
print "*  on /usr2: control/, proc/, sched/, log/, tle_files/, and their contents. *\n";
print "*  The correct owner.group is oper.rtx and permissions is 'ug+rw,o+r,o-w'.  *\n";
print "*                                                                           *\n";
print "*  If you don't want these ownership and permissions, answer 'n' to the     *\n";
print "*  next question.                                                           *\n";
print "*                                                                           *\n";
print "*  You must have root permissions to run this script succesfully            *\n";
print "*****************************************************************************\n";

&y_or_n("Do you want to continue? ") || exit;

&fix("/usr2/control");
&fix("/usr2/proc");
&fix("/usr2/sched");
&fix("/usr2/log");
&fix("/usr2/tle_files");
